//
//  FXKvoEvent.swift
//  FXEvent
//
//  Created by Fanxx on 2021/11/23.
//

import Foundation

/// KVO
open class FXPropertyEvent<ObjectType: NSObject, ValueType>: FXEvent<ValueType> {
    private var observer: NSKeyValueObservation?
    
    public init(for object: ObjectType, keyPath: KeyPath<ObjectType, ParameterType>) {
        super.init()
        self.observer = object.observe(keyPath, options: .new, changeHandler: { [weak self, weak object] _, changed in
            if let value = object?[keyPath: keyPath] {
                self?.sendActions(for: value)
            }
        })
    }
}
/// 在获取事件时动态添加及缓存要获取的事件
@dynamicMemberLookup
public struct FXPropertyChangedEventsWrapper<ObjectType: NSObject> {
    let _fXPropertyChangedEventsWrapObject: ObjectType
    public init(_ base: ObjectType) {
        self._fXPropertyChangedEventsWrapObject = base
    }
    /// 线程安全
    public subscript<ValueType>(dynamicMember keyPath: KeyPath<ObjectType, ValueType>) -> FXPropertyEvent<ObjectType, ValueType> {
        let key = "__fxPropertyChangedEventsWrapper_\(keyPath)"
        return self._fXPropertyChangedEventsWrapObject.extend.object(for: key, createIfNil: FXPropertyEvent(for: self._fXPropertyChangedEventsWrapObject, keyPath: keyPath))
    }
}
public protocol FXPropertyChangedEventable: NSObject {
}
extension FXPropertyChangedEventable {
    /// 可通过此扩展来添加属性变化通知
    public var propertyChanged: FXPropertyChangedEventsWrapper<Self> {
        return .init(self)
    }
}
extension NSObject: FXPropertyChangedEventable {
}
